import { useState, useEffect } from 'react'
import { View, Image, Text, Button } from '@tarojs/components'
import { useRouter } from '@tarojs/taro'
import Taro from '@tarojs/taro'
import { get } from '../../../aiaxios/request'
import { API_BASE_URL } from '../../../../config/env'
import { formatLocalDateTime } from '../../../utils/aidateFormat'
import './TensorFlow.scss'

interface ImageData {
  _id: string
  img: string
  name: string
  uploadTime: string
  originalName?: string
  fileSize?: number
  mimeType?: string
}

export default function TensorFlow() {
  const router = useRouter()
  const [imageData, setImageData] = useState<ImageData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [forceUpdate, setForceUpdate] = useState(0)
  const [rawApiData, setRawApiData] = useState<any>(null) // 用于调试

  // 获取URL参数中的图片ID
  const imageId = router.params.imageId

  console.log('TensorFlow页面渲染，参数:', { imageId, loading, error, imageData })

  // 获取图片数据
  const fetchImageData = async (id: string) => {
    console.log('开始获取图片数据, ID:', id)
    console.log('当前API地址:', API_BASE_URL)
    
    try {
      const response = await get(`/aiimg/getById?id=${id}`)
      console.log('API响应:', response)
      
      if (response && response.code === 200 && response.data) {
        console.log('API返回的完整response:', JSON.stringify(response, null, 2))
        console.log('response.data详细信息:', JSON.stringify(response.data, null, 2))
        console.log('response.data类型:', typeof response.data)
        console.log('response.data的keys:', Object.keys(response.data))
        
        // 直接使用API返回的数据
        const imageData = response.data
        console.log('准备设置的imageData:', JSON.stringify(imageData, null, 2))
        
        // 保存原始API数据用于调试
        setRawApiData(imageData)
        
        // 创建一个新的对象引用，确保React检测到变化
        const newImageData = {
          _id: imageData._id,
          img: imageData.img,
          name: imageData.name,
          uploadTime: imageData.uploadTime,
          originalName: imageData.originalName,
          fileSize: imageData.fileSize,
          mimeType: imageData.mimeType
        }
        
        console.log('创建新的imageData对象:', JSON.stringify(newImageData, null, 2))
        
        // 使用setTimeout确保状态更新不被批处理影响
        setTimeout(() => {
          console.log('延迟设置状态...')
          setImageData(newImageData)
          setError(null)
          setLoading(false)
          setForceUpdate(prev => prev + 1)
          console.log('延迟状态设置完成')
        }, 50)
      } else {
        console.log('API返回错误:', response)
        setError(response?.message || '获取图片信息失败')
      }
    } catch (err: any) {
      console.error('请求失败:', err)
      setError('网络请求失败: ' + (err?.message || '未知错误'))
    }
    
    console.log('设置loading为false')
    setLoading(false)
  }

  // 返回上一页
  const handleGoBack = () => {
    Taro.navigateBack()
  }

  // 重新分析
  const handleReAnalyze = () => {
    // 这里可以添加重新分析的逻辑
    Taro.showToast({
      title: '正在重新分析...',
      icon: 'loading'
    })
  }

  useEffect(() => {
    console.log('useEffect执行，imageId:', imageId)
    if (imageId) {
      fetchImageData(imageId)
    } else {
      setError('缺少图片ID参数')
      setLoading(false)
    }
  }, [imageId])

  // 状态监控
  useEffect(() => {
    console.log('状态变化监控:', { 
      loading, 
      error: !!error, 
      hasImageData: !!imageData, 
      forceUpdate,
      imageDataKeys: imageData ? Object.keys(imageData) : null
    })
  }, [loading, error, imageData, forceUpdate])

  // 构建完整的图片URL
  const getFullImageUrl = (imagePath: string) => {
    if (imagePath.startsWith('http')) {
      return imagePath
    }
    return `${API_BASE_URL}${imagePath}`
  }

  console.log('渲染判断:', { loading, error, imageData, forceUpdate })
  
  if (loading) {
    console.log('渲染loading状态')
    return (
      <View className='tensorflow-container'>
        <View className='loading-container'>
          <Text className='loading-text'>正在加载图片...</Text>
          <Button onClick={() => {
            console.log('手动测试按钮点击')
            setImageData({
              _id: 'test',
              img: '/test.jpg',
              name: '测试图片',
              uploadTime: new Date().toISOString()
            })
            setLoading(false)
          }}>
            测试设置数据
          </Button>
        </View>
      </View>
    )
  }

  if (error || !imageData) {
    return (
      <View className='tensorflow-container'>
        <View className='error-container'>
          <Text className='error-text'>{error || '未找到图片数据'}</Text>
          
          {/* 如果有原始API数据，尝试直接显示 */}
          {rawApiData && (
            <View className='emergency-display'>
              <Text className='debug-title'>应急显示 (使用原始API数据):</Text>
              <Image
                src={`${API_BASE_URL}${rawApiData.img}`}
                className='preview-image'
                mode='aspectFit'
                style={{ width: '200px', height: '200px', margin: '20px auto' }}
              />
              <Text className='debug-text'>图片名称: {rawApiData.name}</Text>
              <Text className='debug-text'>上传时间: {formatLocalDateTime(rawApiData.uploadTime)}</Text>
            </View>
          )}
          
          {/* 网络诊断信息 */}
          <View className='debug-info'>
            <Text className='debug-title'>调试信息:</Text>
            <Text className='debug-text'>当前API地址: {API_BASE_URL}</Text>
            <Text className='debug-text'>图片ID: {imageId || '未获取到'}</Text>
            <Text className='debug-text'>有原始数据: {rawApiData ? '是' : '否'}</Text>
            <Text className='debug-text'>
              环境: {(() => {
                try {
                  const systemInfo = Taro.getSystemInfoSync()
                  return systemInfo.platform === 'devtools' ? '模拟器' : '真机'
                } catch {
                  return '未知'
                }
              })()}
            </Text>
          </View>
          
          <View className='action-buttons'>
            <Button 
              className='retry-button primary' 
              onClick={() => {
                if (imageId) {
                  fetchImageData(imageId)
                } else {
                  setError('图片ID参数缺失，无法重试')
                }
              }}
            >
              重试获取
            </Button>
            <Button 
              className='retry-button secondary' 
              onClick={handleGoBack}
            >
              返回上一页
            </Button>
          </View>
        </View>
      </View>
    )
  }

  return (
    <View className='tensorflow-container'>
      {/* 图片预览区域 */}
      <View className='image-preview-section'>
        <Image
          src={getFullImageUrl(imageData.img)}
          className='preview-image'
          mode='aspectFit'
          onError={() => setError('图片加载失败')}
        />
        <View className='image-info'>
          <Text className='image-name'>{imageData.name}</Text>
          <Text className='upload-time'>
            上传时间: {formatLocalDateTime(imageData.uploadTime)}
          </Text>
          {imageData.originalName && (
            <Text className='original-name'>
              原始文件名: {imageData.originalName}
            </Text>
          )}
        </View>
      </View>

      {/* AI分析结果区域 */}
      <View className='analysis-section'>
        <View className='section-header'>
          <Text className='section-title'>AI智能分析</Text>
        </View>
        <View className='analysis-content'>
          <Text className='analysis-text'>
            正在使用TensorFlow进行图像分析...
          </Text>
          <Text className='analysis-description'>
            我们的AI系统将对您的照片进行深度学习分析，
            包括面部特征识别、美学评估等多个维度。
          </Text>
        </View>
      </View>

      {/* 操作按钮区域 */}
      <View className='action-section'>
        <Button 
          className='action-button primary'
          onClick={handleReAnalyze}
        >
          重新分析
        </Button>
        <Button 
          className='action-button secondary'
          onClick={handleGoBack}
        >
          返回
        </Button>
      </View>
    </View>
  )
}
